/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-10 19:42:10
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-02 21:20:09
 */
import axios, { type AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
import { getStore } from '@/utils/store'
import { useUserStore } from '@/stores/user'
import { close, start } from '@/utils/nprogress'
import router from '@/router/index'
import { useCommonStore } from '@/stores/common'

// axios.defaults.baseURL =
//   import.meta.env.MODE == 'development' ? import.meta.env.VITE_BASE_API : '/'

axios.defaults.withCredentials = true
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

const axiosInstance = axios.create({
	timeout: 10000 * 60,
})
let RequestStatus = true

if (window.location.host == 'mzj.nanjing.gov.cn') {
	axiosInstance.defaults.baseURL = '/nxyl'
} else {
	axiosInstance.defaults.baseURL = import.meta.env.MODE == 'development' ? import.meta.env.VITE_BASE_API : '/'
}

const errorTip = (response?: any, tipMess?: string) => {
	ElMessage({
		showClose: true,
		message: tipMess ? tipMess : showMessage(response.status, response.data!.msg),
		type: 'warning',
	})
}
axiosInstance.interceptors.request.use(
	(config: any) => {
		start()
		config.headers = {
			...config.headers,
			'X-Requested-With': 'XMLHttpRequest',
			'Access-Control-Allow-Origin': '*',
		}
		const access_token = getStore('access_token')
		if (access_token && !config.headers.Authorization) {
			config.headers['Authorization'] = 'Bearer ' + access_token
		}
		const { queryObj } = storeToRefs(useCommonStore())
		if (queryObj.value.subprojectId) {
			config.headers['subprojectId'] = queryObj.value.subprojectId
			config.headers['belongProject'] = queryObj.value.belongProject
		}
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

axiosInstance.interceptors.response.use(
	(response) => {
		close()
		const status = response.status || 200
		if (status === 200) {
			if (response.data?.code == 0 || !response.data?.code) {
				return Promise.resolve(response.data)
			} else {
				errorTip(response)
				return Promise.reject(response.data)
			}
		} else if (status == 401) {
			if (RequestStatus) {
				const { userLoginOut } = useUserStore()
				userLoginOut()
			}
			RequestStatus = false
			return
		} else {
			return Promise.reject(response.data)
		}
	},
	(error) => {
		const { response } = error
		close()
		if (response?.status == 401) {
			if (RequestStatus) {
				const { userLoginOut } = useUserStore()
				userLoginOut()
			}
			RequestStatus = false
			errorTip(response)
		} else if (error?.message?.includes?.('timeout')) {
			errorTip('', '网络连接异常,请稍后再试!')
		} else {
			errorTip(response)
		}
		return Promise.reject(error)
	}
)

const request = <ResponseType = null>(url: string, options?: AxiosRequestConfig<unknown>): Promise<ResponseType> => {
	return new Promise((resolve, reject) => {
		axiosInstance({
			url,
			...options,
		})
			.then((res: any) => {
				resolve(res)
			})
			.catch((err) => reject(err))
	})
}

export { axiosInstance, request }

export const showMessage = (status: Number, msg: String) => {
	let message: String = ''
	switch (status) {
		case 400:
			message = '请求错误(400)'
			break
		case 401:
			message = '未授权，请重新登录(401)'
			break
		case 403:
			message = '拒绝访问(403)'
			break
		case 404:
			message = '请求出错(404)'
			break
		case 408:
			message = '请求超时(408)'
			break
		case 429:
			message = '请求太频繁,请稍后尝试(429)'
			break
		case 500:
			message = '服务器错误(500)'
			// router.push('/500')
			break
		case 501:
			message = '服务未实现(501)'
			break
		case 502:
			message = '网络错误(502)'
			break
		case 503:
			message = '服务不可用,请稍后重试(503)'
			break
		case 504:
			message = '网络超时(504)'
			break
		case 505:
			message = 'HTTP版本不受支持(505)'
			break
		default:
			message = msg
	}
	return `${message}`
}
